from functools import wraps
from django.utils.decorators import available_attrs
from apps.sales_man.models import SalesMan
from .models import ExtendSalesman
from django.http import HttpResponse


def menus_permission():
    # 菜单权限
    def decorator(view_func):
        """django.contrib.auth.decorators重写"""

        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            salesman = request.session["admin_salesman"]
            menus = ExtendSalesman.objects.get(sales=salesman).user_type.menus.filter(show_status=True)
            full_path = request.get_full_path()
            flag = False
            for i in menus:
                for one in i.open_set.all():
                    if one.url in full_path:
                        flag = True
                        i.open_option = "open"
            if not flag:
                return HttpResponse("没有权限访问！！！")
            request.menus = menus
            return view_func(request, *args, **kwargs)

        return _wrapped_view

    return decorator
